<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\UserRule;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }



    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    # 获取用户信息
    public function getData()
    {
        $user = \app\common\model\User::get($this->auth->id);
        $info = [
            'id'=>$user['id'],
            'nickname'=>$user['nickname'],
            'avatar'=>$user['avatar'],
            'money'=>$user['money'],
            'alipay_name'=>$user['alipay_name'],
            'alipay_account'=>$user['alipay_account'],
        ];
        $this->success('获取成功',$info);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->param("platform");
        $code = $this->request->param("code");
        $zhitui_id = $this->request->param('zhitui_id',0);
        $config = get_addon_config('third');

        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        $extend = [];
        if(!empty($zhitui_id)){
            $extend['zhitui_id'] = $zhitui_id;
            }
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result,$extend);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 生成海报
     * @author Created by Xing <464401240@qq.com>
     */
    public function getposter()
    {
        $poster_id = $this->request->param('poster_id');
        $prev_id = DB('poster')->where('id','<',$poster_id)->max('id');
        $next_id = DB('poster')->where('id','>',$poster_id)->min('id');
        $this->model = new \app\admin\model\Poster;
        $image = new \addons\poster\library\Image();
        $list = $this->model->select();
        $data = [];
        foreach ($list as $poster){
            $imgurl = $image->createPosterImage($poster, $this->auth->getUser());
            if (!$imgurl) {
                $this->error('生成海报出错');
            }
            $data[] = [
                'image'=>cdnurl('/' . $imgurl)
            ];
        }
//        $this->model = new \app\admin\model\Poster;
//        $poster = $this->model->get($poster_id);
//        if (!$poster) {
//            $this->error(__('未找到海报' . $poster_id));
//        }

        $this->success('获取成功',$data);
    }

    # 提现
    public function withdraw()
    {
        $user = \app\common\model\User::get($this->auth->id);
        $params = $this->request->param();
        if(empty($params['alipay_name']) || empty($params['alipay_account'])){
            $this->error('请输入支付宝信息');
        }
        if(!$params['money']){
            $this->error('请输入提现金额');
        }
        if(!$user->alipay_name){
            $user->alipay_name = $params['alipay_name'];
            $user->alipay_account = $params['alipay_account'];
            $user->save();
        }
        if($user->money<$params['money']){
            $this->error('大于可提现金额');
        }
        $sxf_bfb = Db('config')->where('name','withdraw_sxf')->value('value');
        $withdraw_day_nums = Db('config')->where('name','withdraw_day_nums')->value('value');
        $withdraw_money_min = Db('config')->where('name','withdraw_money_min')->value('value');
        if($params['money']<$withdraw_money_min){
            $this->error('最低提现金额为'.$withdraw_money_min.'元');
        }
        $is_add = DB('user_withdraw')->where('user_id',$this->auth->id)->where('status',0)->find();
        if(!empty($is_add)){
            $this->error('有正在处理的提现申请');
        }
        $count =  DB('user_withdraw')->where('user_id',$this->auth->id)->whereTime('createtime','today')->where('status','<',2)->count();
        if($count>=$withdraw_day_nums){
            $this->error('每日最多可以提现'.$withdraw_day_nums.'笔');
        }

        $sxf = round($params['money']*$sxf_bfb,2);
        $data = [
            'user_id'=>$this->auth->id,
            'money'=>$params['money'],
            'alipay_name'=>$params['alipay_name'],
            'alipay_account'=>$params['alipay_account'],
            'sxf_price'=>$sxf,
            'true_money'=>round($params['money']-$sxf,2),
            'createtime'=>time(),
            'status'=>0,
        ];
        DB('user_withdraw')->insertGetId($data);
        $this->success('提交成功');
    }

    # 获取提现记录
    public function getWithdrawList()
    {
        $result = DB('user_withdraw')->where('user_id',$this->auth->id)->order('id desc')->paginate(10);
        $total = $result->total();
        $lastpage = $result->lastPage();
        $rows = $result->items();
        $data = [];
        $status = [
            0=>'待审核',
            1=>'已通过',
            2=>'已驳回',
        ];
        foreach ($rows as $v){
            $data[] = [
                'id'=>$v['id'],
                'money'=>$v['money'],
                       'true_money'=>$v['true_money'],
                'sxf_price'=>$v['sxf_price'],
                'des'=>empty($v['des'])?'':$v['des'],
                'createtime'=>date('Y-m-d H::i:s',$v['createtime']),
                'updatetime'=>empty($v['updatetime'])?'':date('Y-m-d H::i:s',$v['updatetime']),
                'status'=>$status[$v['status']],
            ];
        }
        $this->success('获取成功',[
            'lastpage'=>$lastpage,
            'total'=>$total,
            'list'=>$data,
        ]);

    }

    public function getJisuan()
    {
        $params = $this->request->param();

        if(!$params['money']){
            $this->error('请输入提现金额');
        }
        $sxf_bfb = Db('config')->where('name','withdraw_sxf')->value('value');
        $sxf = round($params['money']*$sxf_bfb,2);
        $true_money = round($params['money']-$sxf,2);
        $this->success('获取成功',[
            'bfb'=>$sxf_bfb*100,
            'sxf'=>$sxf,
            'true_money'=>$true_money,
        ]);

    }

    public function getTeam()
    {

        $zhitui_id = $this->auth->zhitui_id;
        $zhitui = [];
        if($zhitui_id){
            $zhitui = DB('user')->where('id',$zhitui_id)->field('id,avatar,nickname')->find();
        }
        $result = DB('user')->where('zhitui_id',$this->auth->id)->field('id,avatar,nickname')->paginate(10);
        $total = $result->total();
        $lastpage = $result->lastPage();
        $rows = $result->items();
        $data = [];
        foreach ($rows as $v){

        }
        $this->success('获取成功',[
            'list'=>$rows,
            'zhitui'=>$zhitui,
            'total'=>$total,
            'lastpage'=>$lastpage,
        ]);
    }

    public function getMoneyLog()
    {
//        \app\common\model\User::money(1000,1,'测试');
        $result = DB('user_money_log')->where('user_id',$this->auth->id)->paginate(10);
        $total = $result->total();
        $lastpage = $result->lastPage();
        $rows = $result->items();
        $data = [];
        foreach ($rows as $v){
            $data[] = [
                'id'=>$v['id'],
                'money'=>$v['money'],
                'memo'=>$v['memo'],
                'createtime'=>date('Y-m-d H:i:s',$v['createtime']),
            ];
        }

        $this->success('获取成功',[
            'list'=>$data,
            'money'=>$this->auth->money,
            'withdraw'=>DB('user_withdraw')->where('user_id',$this->auth->id)->where('status','<',2)->sum('money'),
            'total'=>$total,
            'lastpage'=>$lastpage,
        ]);
    }
}
